<script setup lang="ts">
import { computed, reactive, ref, shallowRef, watch } from 'vue';
import { useFormRules, useNaiveForm } from '@/hooks/common/form';
import type { User } from '@/service/api';
import { createUser, fetchAllDeptOptions, fetchAllPostsOptions, fetchAllRolesOptions, updateUser } from '@/service/api';
import { $t } from '@/locales';
import { DICT_TYPE, getIntDictOptions } from '@/utils/dict';

defineOptions({
  name: 'UserOperateModel'
});

export type OperateType = NaiveUI.TableOperateType;

interface Props {
  /** the type of operation */
  operateType: OperateType;
  /** the edit row data */
  rowData?: User | null;
}

const props = defineProps<Props>();

interface Emits {
  (e: 'submitted'): void;
}

const emit = defineEmits<Emits>();

const visible = defineModel<boolean>('visible', {
  default: false
});

const { formRef, validate, restoreValidation } = useNaiveForm();
const { defaultRequiredRule } = useFormRules();

const submitLoading = ref(false);

const title = computed(() => {
  const titles: Record<OperateType, string> = {
    add: $t('page.manage.user.addUser'),
    edit: $t('page.manage.user.editUser')
  };
  return titles[props.operateType];
});

type Model = Pick<
  User,
  'username' | 'gender' | 'nickname' | 'mobile' | 'email' | 'roles' | 'status' | 'id' | 'remark' | 'deptId' | 'postIds'
>;

const model: Model = reactive(createDefaultModel());

function createDefaultModel(): Model {
  return {
    username: '',
    gender: null,
    nickname: '',
    mobile: '',
    email: '',
    roles: [],
    status: null,
    id: 0,
    remark: '',
    deptId: 0,
    postIds: []
  };
}

type RuleKey = Extract<keyof Model, 'username' | 'status'>;

const rules: Record<RuleKey, App.Global.FormRule> = {
  username: defaultRequiredRule,
  status: defaultRequiredRule
};

const roleOptions = ref<CommonType.Option<string>[]>([]); // 角色列表
const deptOptions = shallowRef<Api.Common.TreeOptions[]>([]); // 部门树
const postOptions = ref([] as Api.Common.Options[]); // 岗位列表

async function getRoleOptions() {
  const { error, data } = await fetchAllRolesOptions();

  if (!error) {
    const options = data.map(item => ({
      label: item.label,
      value: item.value
    }));

    roleOptions.value = [...options];
  }
}

/** 获取部门树，下拉选项 */
async function getDeptTreeOptions() {
  const res = await fetchAllDeptOptions();

  if (!res.error) {
    if (!res.data[0] || !res.data[0].children) {
      deptOptions.value = []; // 或者其他适当的默认值
    } else {
      deptOptions.value = res.data[0].children;
    }
  }
}

async function getPostOptions() {
  const { error, data } = await fetchAllPostsOptions();

  if (!error) {
    postOptions.value = data;
  }
}

function handleInitModel() {
  Object.assign(model, createDefaultModel());

  if (!props.rowData) return;

  if (props.operateType === 'edit') {
    Object.assign(model, props.rowData);
  }
}

function closeDrawer() {
  submitLoading.value = false;
  visible.value = false;
}

async function handleSubmit() {
  await validate();

  submitLoading.value = true;

  if (props.operateType === 'edit') {
    // request
    const { error } = await updateUser(model.id, model);

    if (!error) {
      window.$message?.success($t('common.updateSuccess'));
      closeDrawer();
      emit('submitted');
    }
  } else {
    const { error } = await createUser(model);
    if (!error) {
      window.$message?.success($t('common.addSuccess'));
      closeDrawer();
      emit('submitted');
    }
  }
}

watch(visible, () => {
  if (visible.value) {
    handleInitModel();
    restoreValidation();
    getRoleOptions();
    getDeptTreeOptions();
    getPostOptions();
  }
});
</script>

<template>
  <NModal v-model:show="visible" :title="title" preset="card" class="w-200">
    <NScrollbar class="max-h-200 pr-20px">
      <NForm ref="formRef" :model="model" :rules="rules" label-placement="left" :label-width="100">
        <NFormItem :label="$t('page.manage.user.userName')" path="username">
          <NInput v-model:value="model.username" :placeholder="$t('page.manage.user.form.userName')" />
        </NFormItem>
        <NFormItem :label="$t('page.manage.user.userGender')" path="gender">
          <NRadioGroup v-model:value="model.gender">
            <NRadio
              v-for="item in getIntDictOptions(DICT_TYPE.SYSTEM_USER_SEX)"
              :key="item.value"
              :value="item.value"
              :label="item.label"
            />
          </NRadioGroup>
        </NFormItem>
        <NFormItem :label="$t('page.manage.user.belongingDept')" path="deptId">
          <NTreeSelect
            v-model:value="model.deptId"
            :options="deptOptions"
            :placeholder="$t('page.manage.user.form.belongingDept')"
            key-field="value"
          />
        </NFormItem>
        <NFormItem :label="$t('page.manage.user.nickName')" path="nickname">
          <NInput v-model:value="model.nickname" :placeholder="$t('page.manage.user.form.nickName')" />
        </NFormItem>
        <NFormItem :label="$t('page.manage.user.userPhone')" path="mobile">
          <NInput v-model:value="model.mobile" :placeholder="$t('page.manage.user.form.userPhone')" />
        </NFormItem>
        <NFormItem :label="$t('page.manage.user.userEmail')" path="email">
          <NInput v-model:value="model.email" :placeholder="$t('page.manage.user.form.userEmail')" />
        </NFormItem>
        <NFormItem :label="$t('page.manage.user.userPost')" path="postIds">
          <NSelect
            v-model:value="model.postIds"
            multiple
            filterable
            clearable
            :options="postOptions"
            :placeholder="$t('page.manage.user.form.userPost')"
          />
        </NFormItem>
        <NFormItem :label="$t('page.manage.user.userRemark')" path="remark">
          <NInput v-model:value="model.remark" type="textarea" :placeholder="$t('page.manage.user.form.userRemark')" />
        </NFormItem>
      </NForm>
    </NScrollbar>
    <template #footer>
      <NSpace justify="end" :size="16">
        <NButton @click="closeDrawer">{{ $t('common.cancel') }}</NButton>
        <NButton type="primary" :loading="submitLoading" @click="handleSubmit">{{ $t('common.confirm') }}</NButton>
      </NSpace>
    </template>
  </NModal>
</template>

<style scoped></style>
